/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.retrievedefault;

import com.inspur.edp.bef.api.action.assembler.IMgrActionAssembler;
import com.inspur.edp.bef.api.be.IBEManagerContext;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.api.exceptions.BefException;
import com.inspur.edp.bef.api.exceptions.ErrorCodes;
import com.inspur.edp.bef.api.parameter.retrieve.RetrieveParam;
import com.inspur.edp.bef.core.action.AuthorityUtil;
import com.inspur.edp.bef.core.action.base.ActionUtil;
import com.inspur.edp.bef.core.be.BusinessEntity;
import com.inspur.edp.bef.core.lock.LockUtils;
import com.inspur.edp.bef.core.session.FuncSessionManager;
import com.inspur.edp.bef.entity.exception.ExceptionLevel;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.udt.entity.IUdtData;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import org.springframework.util.StringUtils;

public class RetrieveDefaultChildMgrAction extends AbstractManagerAction<IEntityData>
{

		//region Consturctor

	public RetrieveDefaultChildMgrAction(IBEManagerContext managerContext, List<String> nodeCodes,
			List<String> hierachyIdList, String dataID, Map<String, Object> values) {
		ActionUtil.requireNonNull(nodeCodes, "nodeCodes不能为空");
		ActionUtil.requireNonNull(hierachyIdList, "hierachyIdList不能为空");
		this.nodeCodes = nodeCodes;
		this.hierachyIdList = hierachyIdList;
		this.dataID = dataID;
		this.values = values;
	}
		//endregion

		//region 字段属性

	private java.util.List<String> nodeCodes;
	private java.util.List<String> hierachyIdList;
	private String dataID;
	private Map<String, Object> values;

		//endregion

		//region Override

	@Override
	public final void execute()
	{
		getBEManagerContext().checkAuthority("Modify");
//		AuthorityUtil.checkAuthority("Modify");
//		FuncSessionManager.getCurrentSession().getBefContext().setCurrentOperationType("Modify");
IBusinessEntity be = getBEManagerContext().getEntity(hierachyIdList.get(0));

		RetrieveParam tempVar = new RetrieveParam();
		tempVar.setNeedLock(true);
		if(be.retrieve(tempVar).getData() == null){
				throw new BefException(ErrorCodes.ModifyingNonExistence, "新增子时主表数据不存在" + hierachyIdList.get(0), null, ExceptionLevel.Error);
		}
		LockUtils.checkLocked(be.getBEContext());
		//if (!com.inspur.edp.bef.core.be.BEContext.isLocked())
		//    throw new BizMessageException(ErrorCodes.EditingLocked, new BizMessage
		//    {
		//        MessageFormat = "数据已被其他用户锁定无法执行当前操作",
		//        Location = new MessageLocation { NodeCode = "", DataIds = new List<string> { com.inspur.edp.bef.core.be.ID } },
		//        Level = MessageLevel.Error
		//    });

		IEntityData result = doRetrieveDefaultChild(be);
		modifyByDefaultValue(be, result);
		setResult(result);
		//Result = com.inspur.edp.bef.core.be.BEContext.CurrentData;
	}

	private void modifyByDefaultValue(IBusinessEntity be, IEntityData childData) {
		if (values == null || values.isEmpty()) {
			return;
		}
		ModifyChangeDetail childChange = new ModifyChangeDetail(childData.getID());
		for (Entry<String, Object> pair : values.entrySet()) {
			if (pair.getValue() != null && pair.getValue() instanceof IUdtData) {
				continue;
			}
			childChange.getPropertyChanges().put(pair.getKey(), pair.getValue());
		}
		if (childChange.getPropertyChanges().isEmpty()) {
			return;
		}

		ModifyChangeDetail currentChange = childChange;
		for (int i = hierachyIdList.size() - 1; i >= 0; i--) {
			String nodeCode = nodeCodes.get(i);
			ModifyChangeDetail change = new ModifyChangeDetail(hierachyIdList.get(i));
			change.addChildChangeSet(nodeCode, currentChange);
			currentChange = change;
		}

		be.modify(currentChange);
	}

	public IEntityData doRetrieveDefaultChild(IBusinessEntity be) {
		if (!StringUtils.isEmpty(dataID) || values != null) {
			return ((BusinessEntity)be).retrieveDefaultChild(nodeCodes, hierachyIdList, dataID, values);
		} else {
			return be.retrieveDefaultChild(nodeCodes, hierachyIdList);
		}
	}

	@Override
	protected final IMgrActionAssembler getMgrAssembler()
	{
		return getMgrActionAssemblerFactory().getRetrieveDefaultChildMgrActionAssembler(getBEManagerContext(), nodeCodes, hierachyIdList);
	}
	//endregion
}
